import 'dart:convert';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/handover_new_area_entity.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/a_yyt/page/pending_single_Staff_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';

import '../../util/flat_button.dart';



class HandoverRecordPage extends StatefulWidget {
  final HandoverElderInfo? info;
  final String? customerElderName;
  final String? roomNo;
  final VoidCallback? callBack;
  HandoverRecordPage({
    Key? key,
    this.info,
    this.customerElderName,
    this.roomNo,
    this.callBack,
  });
  @override
  _HandoverRecordPageState createState() => _HandoverRecordPageState();
}

class _HandoverRecordPageState extends State<HandoverRecordPage> {
  TextEditingController textFieldEditer = TextEditingController();
  TextEditingController textUpdateFieldEditer = TextEditingController();
  FocusNode textFocusNode = FocusNode();
  bool _isFocus = false;
  bool _isNotifOther = false;
  int? _recordId;
  List<PendingSelectedGroupEntity> orginList = [];
  List<String> _staffNameList = [];
  List<int> _staffIdList = [];

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getAllByCurBranchWithUsers();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:
            Text('${widget.customerElderName ?? ''}  ${widget.roomNo ?? ''}'),
        elevation: 0.5,
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.fromLTRB(15, 15, 15, 0),
          width: ScreenUtil.getScreenW(context),
          height: ScreenUtil.getScreenH(context) -
              ScreenUtil.getInstance().appBarHeight -
              ScreenUtil.getStatusBarH(context),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '${widget.info?.content ?? ''}',
                style: TextStyles.textDark18,
              ),
              Gaps.vGap15,
              Flexible(
                child: ((widget.info?.records??[]).isNotEmpty)
                    ? ListView.separated(
                        itemCount: widget.info!.records!.length,
                        itemBuilder: (context, index) {
                          return Container(
                            margin: EdgeInsets.only(bottom: 10),
                            padding: EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color: Colours.bg_color,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text(
                                      '${widget.info!.records![index].operator}  ${DateUtil.formatDateStr(widget.info!.records![index].createdDate??"", format: DateFormats.mo_d_h_m)}',
                                      style: TextStyles.textGray16,
                                    ),
                                    Gaps.hGap12,
                                    Gaps.hGap12,
                                    widget.info!.records![index].focus == 1
                                        ? SizedBox(
                                            height: 25,
                                            child: Chip(
                                              padding: EdgeInsets.only(
                                                  bottom: 7, left: 5, right: 5),
                                              label: Text('重要'),
                                              labelStyle: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 13),
                                              backgroundColor: Colors.red,
                                            ),
                                          )
                                        : SizedBox(),
                                    Expanded(child: SizedBox()),
                                    widget.info!.records![index].operAuth==true
                                        ? GestureDetector(
                                            behavior: HitTestBehavior.opaque,
                                            onTap: () {
                                              _recordId =
                                                  widget.info!.records![index].id;
                                              _bottomAddReportArchiveSheetAlert(
                                                  true);
                                            },
                                            child: Text(
                                              '修改',
                                              style: TextStyle(
                                                fontSize: 16,
                                                color: Colors.blue[300],
                                              ),
                                            ),
                                          )
                                        : SizedBox(),
                                    Gaps.hGap12,
                                    Gaps.hGap12,
                                    widget.info!.records![index].operAuth==true
                                        ? GestureDetector(
                                            behavior: HitTestBehavior.opaque,
                                            onTap: () {
                                              _deleteExpertRecordData(widget
                                                  .info!.records![index].id??0);
                                            },
                                            child: Text(
                                              '删除',
                                              style: TextStyle(
                                                fontSize: 16,
                                                color: Colors.red[300],
                                              ),
                                            ),
                                          )
                                        : SizedBox(),
                                  ],
                                ),
                                Gaps.vGap12,
                                Text(
                                  '${widget.info!.records![index].remark}',
                                  style: TextStyles.textDark16,
                                ),
                              ],
                            ),
                          );
                        },
                        separatorBuilder: (context, index) => Gaps.line,
                      )
                    : Center(
                        child: Text('暂无数据'),
                      ),
              ),
              Gaps.vGap5,
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        _bottomAddReportArchiveSheetAlert(false);
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Text(
                        TextUtil.isEmpty(textFieldEditer.text)
                            ? '请输入专家意见'
                            : textFieldEditer.text,
                        style: TextStyle(
                          color: Colours.text_gray,
                        ),
                      ),
                    ),
                  ),
                  FlatsButton(
                    onPressed: () {
                      _sendExpertRecordData(false);
                    },
                    child: Text(
                      '发送',
                      style: TextStyle(
                        color: Colors.blue,
                        fontSize: 16,
                      ),
                    ),
                  ),
                ],
              ),
              Gaps.vGap5,
            ],
          ),
        ),
      ),
    );
  }

  ///获取分组
  void _getAllByCurBranchWithUsers() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.getAllByCurBranchWithUsers)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            PendingSelectedGroupSection model =
                PendingSelectedGroupSection.fromJson(map);
            orginList = model.data??[];
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///新增、更新 - 专家意见
  _sendExpertRecordData(bool isUpdate) {
    if (TextUtil.isEmpty(textFieldEditer.text) && isUpdate == false) {
      Toast.show('请输入专家意见');
      return;
    }
    if (TextUtil.isEmpty(textUpdateFieldEditer.text) && isUpdate) {
      Toast.show('请输入专家意见');
      return;
    }
    Map map = {
      // 'dutyInfoId': widget.info.id,
      // 'remark': textFieldEditer.text,
      'focus': _isFocus ? 1 : 0,
    };
    if (_staffNameList.length > 0) {
      map['notifyHumanIds'] = _staffIdList;
    }
    isUpdate
        ? map['remark'] = textUpdateFieldEditer.text
        : map['remark'] = textFieldEditer.text;
    isUpdate ? map['id'] = _recordId : map['dutyInfoId'] = widget.info?.id??0;
    // 'notifyHumanIds' 通知人员
    //  shiftingDutyRecordUpdateBean
    String url = isUpdate
        ? HttpApi.shiftingDutyRecordUpdateBean
        : HttpApi.shiftingDutyRecordCreate;
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post('$url', data: jsonEncode(map)).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          textFieldEditer.text = '';
          textUpdateFieldEditer.text = '';
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///删除意见
  _deleteExpertRecordData(int id) {
    var map = {'id': id};
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.shiftingDutyRecordDelete}',
            data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///输入专家意见
  _bottomAddReportArchiveSheetAlert(bool isUpdate) {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: true,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            return SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.only(
                    bottom: MediaQuery.of(context).viewInsets.bottom),
                child: Column(
                  children: <Widget>[
                    Gaps.vGap16,
                    Text(
                      isUpdate ? '修改专家意见' : '新增专家意见',
                      style: TextStyle(fontSize: 20, color: Colours.text_dark),
                    ),
                    Gaps.vGap15,
                    Container(
                      constraints: BoxConstraints(
                        maxHeight: 200.0,
                        minHeight: 50.0,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                      padding: EdgeInsets.fromLTRB(15, 10, 15, 5),
                      child: TextField(
                        controller:
                            isUpdate ? textUpdateFieldEditer : textFieldEditer,
                        maxLines: null,
                        keyboardType: TextInputType.multiline,
                        autofocus: false,
                        focusNode: textFocusNode,
                        decoration: InputDecoration.collapsed(
                          hintText: "请输入您的专家意见",
                        ),
                      ),
                    ),
                    Gaps.vGap12,
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Gaps.hGap15,
                        ChoiceChip(
                          selected: _isFocus,
                          selectedColor: Colors.red[300],
                          backgroundColor: Colours.text_gray,
                          label: Text(
                            '重要',
                            style: TextStyle(color: Colors.white),
                          ),
                          onSelected: (value) {
                            setDialogState(() {
                              _isFocus = value;
                            });
                          },
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(3.0),
                          ),
                        ),
                        Gaps.hGap15,
                        ChoiceChip(
                          selected: _isNotifOther,
                          selectedColor: Colors.blue[300],
                          backgroundColor: Colours.text_gray,
                          label: Text(
                            '通知人员',
                            style: TextStyle(color: Colors.white),
                          ),
                          onSelected: (value) {
                            setState(() {
                              _isNotifOther = value;
                              if (value) {
                                textFocusNode.unfocus();
                                AppNavigator.push(
                                  context,
                                  PendingSingleStaffPage(
                                    orginList: orginList,
                                    callBack: (selectedList) {
                                      setState(() {
                                        // _selectedList = selectedList;
                                        if (selectedList.length > 0) {
                                          _staffNameList.clear();
                                          _staffIdList.clear();
                                          for (var item in selectedList) {
                                            _staffNameList.add(item.userName??"");
                                            _staffIdList.add(item.userId??0);
                                          }
                                        }
                                      });
                                    },
                                  ),
                                );
                              }
                            });
                          },
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(3.0),
                          ),
                        ),
                        Expanded(child: SizedBox()),
                        FlatsButton(
                          onPressed: () {
                            Navigator.pop(context);
                            _sendExpertRecordData(isUpdate);
                          },
                          child: Text(
                            '发送',
                            style: TextStyle(color: Colors.blue),
                          ),
                        ),
                      ],
                    ),
                    Gaps.vGap5,
                    (_staffNameList.length > 0 && _isNotifOther)
                        ? Text('${_staffNameList.join('，')}')
                        : SizedBox(),
                    Gaps.vGap15,
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }
}
